package com.kele.controller;

import com.kele.domain.Blog;
import com.kele.domain.User;
import com.kele.domain.pageInfo;
import com.kele.service.BlogService;
import com.kele.service.UserService;
import com.kele.utils.PageUtil;
import com.kele.utils.ResponseData;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/blogs")
public class BlogsController {

    @Resource
    private BlogService blogService;
    @Resource
    private UserService userService;

    /**
     * @author 栗守佳
     * @param model
     * @param pageNum
     * @return
     * 查询所有博客
     */
    @RequestMapping(value = "/findBlogs", method = RequestMethod.GET)//已经实现
    public String findBlogs(Model model,
                            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                            @RequestParam(value = "dataNums", defaultValue = "5") int dataNums,
                            @RequestParam(value = "pageBarSize", defaultValue = "5") int pageBarSize,
                            @RequestParam(value = "flag", defaultValue = "1") int flag) {
        int count = userService.findAllSize("blog", flag);
        System.out.println(count);
        PageUtil pageUtil = new PageUtil(pageNum, count, dataNums);
        pageNum = pageUtil.getPageNum();
        int start = pageUtil.getStart();
        List<Blog> blogs = blogService.findBlogs(start, dataNums);
        pageInfo pageInfo = new pageInfo(blogs, pageNum, count, dataNums, pageBarSize);
        System.out.println(pageInfo);
        model.addAttribute("pageInfo", pageInfo);
        return "static_resources/templates/article";
    }

    /**
     * 查看更多博客
     * @param model
     * @return
     */
    @RequestMapping(value = "/checkBlog",method = RequestMethod.GET)
    public String checkBlog(Model model,
                            @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                            @RequestParam(value = "dataNums",defaultValue = "5") int dataNums,
                            @RequestParam(value = "pageBarSize",defaultValue = "5")int pageBarSize,
                            @RequestParam(value = "flag",defaultValue = "1") int flag){
        int count =userService.findAllSize("blog",flag);
        PageUtil pageUtil=new PageUtil(pageNum,count,dataNums);
        pageNum=pageUtil.getPageNum();
        List<Blog> blogs = blogService.findBlogs(pageNum,pageBarSize);
        pageInfo pageInfo=new pageInfo(blogs,pageNum,count,dataNums,pageBarSize);
        System.out.println(pageInfo);
        model.addAttribute("pageInfo",pageInfo);

        return "static_resources/templates/checkBlog";

    }

    /**
     * @author 栗守佳
     * @param model
     * @param field
     * @return java.lang.String
     * @description 2021/5/27 23:19 前台的全局搜索
     */
    @RequestMapping("/findByTitle")
    public String findByTitle(Model model, String field) {
        System.out.println(field);
        List<Blog> blogs = blogService.findByTitle(field);//执行根据名字查询的方法
        System.out.println("blogs" + blogs);
        model.addAttribute("blog", blogs);
        return "/static_resources/templates/search";
    }


    /**
     * @author 栗守佳
     * @param
     * @param model
     * @return
     * 点击文章进入阅读页面,同时显示博主文章数
     */
    @RequestMapping("/findById")
    public String findById(@Param("bid") int bid,
                           @Param(value = "id") int id,
                           Model model){
        System.out.println(bid);
        Blog blog = blogService.queryById(bid,id);
        User user=userService.queryUserById(id);
        System.out.println(user);
        blogService.addDoh(blog.getBid());
        //展示该博主的文章数量
        int count = blogService.countArticle(blog.getBlogger());
        model.addAttribute("count", count);
        model.addAttribute("blog", blog);
        model.addAttribute("user",user);
        return "static_resources/templates/read";
    }


    /**
     * @author 栗守佳
     * @param id
     * @return java.lang.String
     * 根据id删除博客文章
     */
    @RequestMapping(value = "/deleteBlog", method = RequestMethod.GET)
    public String deleteBlog(int id, HttpServletRequest request) {
        blogService.deleteBlog(id);
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int total = Integer.parseInt(request.getParameter("total"));
        if (total - 1 <= 0) {
            pageNum = pageNum - 1;
            if (pageNum == 0) {
                pageNum = 1;
            }
        }
        System.out.println(total);
        return "redirect:/blogs/findBlogs?pageNum=" + pageNum;
    }

    /**
     * @author 栗守佳
     * @param model
     * @return
     * 博主个人中心博客遍历
     */
    @RequestMapping(value = "/findBlogsByBlogger", method = RequestMethod.GET)
    public String findBlogsByBlogger(Model model, HttpServletRequest request, String blogger) {
        User user = (User) request.getSession().getAttribute("User");
        blogger = user.getNickname();
        System.out.println(blogger);
        List<Blog> blogs = blogService.findBlogsByBlogger(blogger);
        System.out.println(blogs);
        model.addAttribute("people", blogs);
        return "static_resources/templates/contentManagement";
    }

    /**
      *@author 赵奥林
      *@description 2021/5/27 23:20 //取消点赞（-1）
     * @param id
     * @return java.lang.String
      */
    @RequestMapping(value = "/subthumbsUp",method = RequestMethod.GET)
    public String subthumbsUp(int id){
        blogService.subThumbsUp(id);
        return "1";
    }



//    /**
//     * 查看更多博客
//     * @author 赵奥林
//     * @param model
//     * @return
//     */
//    @RequestMapping(value = "/checkBlog",method = RequestMethod.GET)
//    public String checkBlog(Model model,
//                            @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
//                            @RequestParam(value = "dataNums",defaultValue = "5") int dataNums,
//                            @RequestParam(value = "pageBarSize",defaultValue = "5")int pageBarSize,
//                            @RequestParam(value = "flag",defaultValue = "1") int flag){
//        int count =userService.findAllSize("blog",flag);
//        PageUtil pageUtil=new PageUtil(pageNum,count,dataNums);
//        pageNum=pageUtil.getPageNum();
//        List<Blog> blogs = blogService.findBlogs(pageNum,pageBarSize);
//        pageInfo pageInfo=new pageInfo(blogs,pageNum,count,dataNums,pageBarSize);
//        System.out.println(pageInfo);
//        model.addAttribute("pageInfo",pageInfo);
//
//        return "static_resources/templates/checkBlog";
//
//    }

    /**
     * 展示博客到主页面上
     * @author 赵奥林
     * @param model
     * @return
     */
    @RequestMapping(value = "/showBlogs", method = RequestMethod.GET)
    public String showBlogs(Model model) {

        List<Blog> blogs = blogService.showBlogs();

        //新的list集合储存取出来的数据
        List<Blog> list=new ArrayList<Blog>();
        if(blogs.size()<6){
            list=blogs;
        }else {

        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int intRandom = random.nextInt(blogs.size() - 1);
            list.add(blogs.get(intRandom));
            blogs.remove(blogs.get(intRandom));
        }
        }
        model.addAttribute("blogs",list);
        return "static_resources/templates/index";
    }


    /**
     * 查询一个差的博客类
     * @author 王箫凯
     * @param blogger 博主名称
     * @param model   数据传输
     * @param request 获得session
     * @return 返回到遍历页面
     */
    @RequestMapping(value = "/findAcBlogs", method = RequestMethod.GET)
    public String selectBadBlogs(@Param("blogger") String blogger,
                                 @Param("bid") int bid, Model model,
                                 HttpServletRequest request) {
        //获取博客对象，得到博主的基本信息
        Blog blogs = blogService.undeterminedBlogs(blogger, bid);
        //获取session
        User user = (User) request.getSession().getAttribute("User");
        if (!blogger.equals(user.getNickname()) || user.getVip() < 2) {
            //说明博主与该用户是同一个用户 或者为管理员
            blogs.setTitle("该文章不存在!");
            blogs.setDoh(0);
            blogs.setCollection(0);
            blogs.setThumbsup(0);
            blogs.setContent("");
        }
        model.addAttribute("blog", blogs);
        return "static_resources/templates/read";
    }

    /**
     * 管理员浏览正在审核中的博客
     * 详细解析：
     * 1. 如果不含参数，则为管理员遍历 包含所有
     * 2. 如果含有等级小于2 即为普通用户，则是对自己正在审核中的博客信息进行遍历
     * 3. 如果vip<2 含有两个参数，则是对响应博客的浏览
     *
     * @author 王箫凯
     * @param blogger 博主的昵称
     * @param request 接收session
     * @param bid     博客的内容
     * @param model   数据转发
     * @param flag    判断文章类型，默认为0，表示的是浏览正在审批审批的用户，1表示已经通过审批的文章，2表示未通过审批的文章
     * @return 返回页面
     */
    @RequestMapping("/findAbBlogs")
    public String selectExamineBlogs(@RequestParam(value = "blogger", defaultValue = "") String blogger,
                                     @RequestParam(value = "bid", defaultValue = "-1") int bid,
                                     @RequestParam(value = "flag", defaultValue = "0") int flag,
                                     @RequestParam(value = "vip", defaultValue = "0") int vip,
                                     HttpServletRequest request, Model model) {
        List<Blog> list = null;
        //获取session
        User user= (User) request.getSession().getAttribute("User");
        //先判断bid是否大于0，如果大于0，则表示对单个文章的阅读,反之则是对部分文章的遍历
        //表示管理员浏览
        if (vip==1){
            //是遍历
            if (bid<=0){
                blogger="";
                list= blogService.selectExamineBlogs(blogger, bid,flag);
                model.addAttribute("list",list);
                return "/static_resources/templates/verify";
            }else {
                //不是遍历，而是单个查询
                list= blogService.selectExamineBlogs(blogger, bid,flag);
                Blog blog= list.get(0);
                model.addAttribute("blog",blog);
                System.out.println("2==="+blog);
                return "static_resources/templates/read";
            }
        } else {
            //普通用户查询
            if (bid <= 0) {
                //普通的遍历
                if (blogger.equals(user.getNickname())) {
                    list = blogService.selectExamineBlogs(blogger, bid, flag);
                    model.addAttribute("list", list);
                    System.out.println("3==" + list);
                    return "个人用户遍历界面";

                } else {
                    model.addAttribute("list", list);
                    System.out.println("5==" + list);
                    return "个人查看自己文章的界面";
                }
            } else {
                //普通用户的阅读
                if (blogger.equals(user.getNickname())) {
                    //表示为 本人查看自己的审核中的文章
                    list = blogService.selectExamineBlogs(blogger, bid, flag);
                    model.addAttribute("list", list);
                    System.out.println("4==" + list);
                    return "个人查看自己文章的界面";
                }else {
                    Blog blog= list.get(0);
                    model.addAttribute("blog",blog);
                    System.out.println("5=="+list);
                    return "个人查看自己文章的界面";
                }
            }
        }

    }

    /**
     * @author 王箫凯
     * @param model
     * @return
     */
    @RequestMapping(value = "/classify")
    public String classify(Model model) {
        Map<String, Object> classifiedMap = new HashMap<String, Object>();
        Random random = new Random();
        String[] type = {"生", "二", "音", "美", "影", "运", "科", "技", "社", "其"};
        String[] typeName = {"life", "two", "music", "food", "movie", "sport", "science", "technology", "friend", "other"};
        for (int i = 0; i < type.length; i++) {
            List<Blog> blogs = blogService.classify(type[i]);
            List<Blog> list = new ArrayList<Blog>();
            //随机展示博客
            if (blogs.size() >= 4) {
                for (int j = 0; j < 4; j++) {
                    int intRandom = random.nextInt(blogs.size() - 1);
                    list.add(blogs.get(intRandom));
                    blogs.remove(blogs.get(intRandom));
                }
            } else {
                list = blogs;
            }
            classifiedMap.put(typeName[i], list);
        }
        model.addAttribute("classifiedMap", classifiedMap);
        System.out.println(classifiedMap);
        return "static_resources/templates/classify";
    }

    @GetMapping(value = "/findBlogsByBid")
    public String findBlogsByBid(Model model,HttpServletRequest request,@Param("bid")int bid){
        Blog blogs=blogService.findBlogsByBid(bid);
        int count= blogService.countArticle(blogs.getBlogger());
//        User users=userService.queryUserById();
        model.addAttribute("count",count);
        model.addAttribute("blog",blogs);
        return "static_resources/templates/read";
    }

}
